import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import javax.crypto.SealedObject;


public class PointOfSale {

	public void listenClient() {
		try {
			ServerSocket ss = new ServerSocket(55555);
			s = ss.accept();
			os = s.getOutputStream();
			oos = new ObjectOutputStream(os);
			is = s.getInputStream();
			ois = new ObjectInputStream(is);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void disconnect() {
		try {
			os.close();
			oos.close();
			is.close();
			ois.close();
			s.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private Socket s;
	private OutputStream os;
	private InputStream is;
	private ObjectOutputStream oos;
	private ObjectInputStream ois;
	
	
	// Need to be connected to a client
	public EncryptedBankObject getEncryptedBankTicket(Receipt receipt, Long sellerId, Long nonce) {
		EncryptedBankObject encryptedBankTicket = null;
		try {
			oos.writeObject(receipt);
			// Wait for validation
			int reply = (Integer) ois.readObject();
			if (reply == 1) {
				oos.writeObject(sellerId);
				oos.writeObject(nonce);
				// Wait for bank ticket
				encryptedBankTicket = (EncryptedBankObject) ois.readObject();
			}
			else { // Payment refused
				disconnect();
			}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		return encryptedBankTicket;
	}
	
	// Simulation
	public Receipt generateReceipt() {
		Receipt r = new Receipt();
		r.addEntry("Coke 2L", 2, 2); // 2 bottles
		r.addEntry("Cookies", 3, 2);
		return r;
	}
	
	public static void main(String[] args) {
		PointOfSale pos = new PointOfSale();
		Receipt receipt = pos.generateReceipt();
		pos.listenClient();
		pos.getEncryptedBankTicket(receipt, sellerId, nonce);
	}
	
}
